<template>
  <div class="article-form-container">
    <el-card class="article-form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Edit /></el-icon>
          <span class="header-title">{{ isEditMode ? '编辑文章' : '新建文章' }}</span>
          <el-tag :type="isEditMode ? 'success' : 'primary'" class="header-tag">
            {{ isEditMode ? '编辑模式' : '创建模式' }}
          </el-tag>
        </div>
      </template>
      
      <el-form
        ref="articleFormRef"
        :model="form"
        :rules="articleRules"
        label-width="100px"
        class="article-form"
      >
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="文章标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入文章标题"
                maxlength="200"
                show-word-limit
                clearable
                size="large"
                class="title-input"
              >
                <template #prepend>
                  <el-icon><Document /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="URL标识" prop="slug">
              <el-input
                v-model="form.slug"
                placeholder="URL友好的标题标识,如my-first-post"
                maxlength="200"
                show-word-limit
                @blur="generateSlugIfEmpty"
                clearable
              >
                <template #prepend>
                  <el-icon><Link /></el-icon>
                </template>
                <template #append>
                  <el-button @click="generateSlugIfEmpty" type="primary">自动生成</el-button>
                </template>
              </el-input>
              <div class="form-item-hint">
                <el-text size="small" type="info"> 留空将自动从标题生成 </el-text>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="文章摘要" prop="summary">
              <el-input
                v-model="form.summary"
                type="textarea"
                placeholder="请输入文章摘要"
                :rows="3"
                maxlength="500"
                show-word-limit
                resize="vertical"
                class="summary-textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="封面图片">
              <div class="cover-upload-container">
                <el-input
                  v-model="form.coverImage"
                  placeholder="请输入封面图片URL"
                  clearable
                >
                  <template #prepend>
                    <el-icon><Picture /></el-icon>
                  </template>
                </el-input>
                <el-upload
                  class="upload-cover"
                  action="/upload"
                  :on-success="handleCoverUploadSuccess"
                  :show-file-list="false"
                >
                  <el-button size="small" type="primary">
                    <el-icon><Upload /></el-icon>
                    上传
                  </el-button>
                </el-upload>
              </div>
              
              <div v-if="form.coverImage" class="cover-preview">
                <el-image 
                  :src="form.coverImage" 
                  class="cover-image"
                  fit="cover"
                  :preview-src-list="[form.coverImage]"
                  :preview-teleported="true"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="form.coverImage = ''"
                  class="remove-cover-btn"
                >
                  <el-icon><Delete /></el-icon>
                  移除
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="文章内容" prop="content">
              <!-- 添加富文本编辑器切换按钮的点击事件 -->
              <el-button 
                size="small" 
                type="primary" 
                plain 
                @click="toggleEditor"
                class="editor-toggle-btn"
              >
                <el-icon>
                  <MagicStick v-if="!isRichTextEditor" />
                  <Document v-else />
                </el-icon>
                {{ !isRichTextEditor ? '切换到富文本编辑器' : '切换到普通编辑器' }}
              </el-button>
              
              <!-- 富文本编辑器 -->
              <div v-show="isRichTextEditor" class="editor-wrapper">
                <QuillEditor
                  v-model="form.content"
                  contentType="html"
                  theme="snow"
                  :options="editorOption"
                  class="rich-text-editor"
                />
              </div>

              <!-- 普通文本编辑器 -->
              <el-input
                v-show="!isRichTextEditor"
                v-model="form.content"
                type="textarea"
                placeholder="请输入文章内容(支持Markdown或HTML)"
                :autosize="{ minRows: 15, maxRows: 30 }"
                resize="vertical"
                class="content-textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 添加间距以防止重叠 -->
        <div class="form-spacing"></div>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status" class="status-radio-group">
                <el-radio-button label="published" border>
                  <el-icon><Select /></el-icon>
                  已发布
                </el-radio-button>
                <el-radio-button label="draft" border>
                  <el-icon><DocumentCopy /></el-icon>
                  草稿
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="评论状态">
              <el-radio-group v-model="form.commentStatus" class="status-radio-group">
                <el-radio-button label="open" border>
                  <el-icon><ChatLineSquare /></el-icon>
                  开放评论
                </el-radio-button>
                <el-radio-button label="closed" border>
                  <el-icon><Lock /></el-icon>
                  关闭评论
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="是否置顶">
              <el-switch
                v-model="form.isTop"
                active-value="1"
                inactive-value="0"
                active-text="置顶"
                inactive-text="普通"
                inline-prompt
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12" v-if="form.status === 'published'">
            <el-form-item label="发布时间">
              <el-date-picker
                v-model="form.publishedAt"
                type="datetime"
                placeholder="选择发布时间"
                :default-time="defaultTime"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="publish-date-picker"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="SEO元数据">
              <el-input
                v-model="form.metaData"
                type="textarea"
                placeholder='{"keywords": ["关键词1", "关键词2"], "description": "描述内容"}'
                :rows="3"
                resize="vertical"
                class="metadata-textarea"
              />
              <div class="form-item-hint">
                <el-text size="small" type="info"> 请输入JSON格式的元数据 </el-text>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item class="form-actions">
              <div class="action-buttons">
                <el-button @click="resetForm" size="large">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
                <el-button type="primary" @click="submitForm" size="large" class="submit-button">
                  <el-icon><Check /></el-icon>
                  保存文章
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, defineExpose, defineProps, defineEmits, computed } from "vue";
import { submitArticleService } from "@/api/post.js";
import {
  Edit,
  Document,
  Link,
  Picture,
  Upload,
  Delete,
  MagicStick,
  Select,
  DocumentCopy,
  ChatLineSquare,
  Lock,
  Refresh,
  Check
} from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

export default {
  name: "ArticleForm",
  components: {
    Edit,
    Document,
    Link,
    Picture,
    Upload,
    Delete,
    MagicStick,
    Select,
    DocumentCopy,
    ChatLineSquare,
    Lock,
    Refresh,
    Check,
    QuillEditor,
  },
  props: {
    modelValue: {
      type: Object,
      default: () => ({
        title: "",
        slug: "",
        summary: "",
        coverImage: "",
        content: "",
        status: "draft",
        commentStatus: "open",
        isTop: 0,
        metaData: "",
        publishedAt: "",
      })
    }
  },
  emits: ['update:modelValue', 'submit'],
  setup(props, { emit }) {
    const articleFormRef = ref(null);
    const defaultTime = new Date();

    // 使用 props 作为表单数据源
    const form = reactive({ ...props.modelValue });
    
    // 计算是否为编辑模式
    const isEditMode = computed(() => {
      return props.modelValue && props.modelValue.id;
    });

    // 添加富文本编辑器状态
    const isRichTextEditor = ref(true); // 默认启用富文本编辑器

    // 添加富文本编辑器选项
    const editorOption = {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered'}, { 'list': 'bullet' }],
          [{ 'script': 'sub'}, { 'script': 'super' }],
          [{ 'indent': '-1'}, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean'],
          ['link', 'image', 'video']
        ]
      },
      placeholder: '请输入文章内容...',
      theme: 'snow'
    }

    // 切换编辑器
    const toggleEditor = () => {
      isRichTextEditor.value = !isRichTextEditor.value;
    };
    
    // 表单验证规则
    const articleRules = {
      title: [
        { required: true, message: "文章标题不能为空", trigger: "blur" },
        {
          min: 2,
          max: 200,
          message: "标题长度在2到200个字符之间",
          trigger: "blur",
        },
      ],
      slug: [
        { required: true, message: "文章别名不能为空", trigger: "blur" },
        {
          pattern: /^[a-z0-9]+(?:-[a-z0-9]+)*$/,
          message:
            "别名只能包含小写字母、数字和连字符'-'，且不能以连字符开头或结尾",
          trigger: "blur",
        },
        {
          min: 3,
          max: 200,
          message: "别名长度在3到200个字符之间",
          trigger: "blur",
        },
      ],
      summary: [
        { required: true, message: "文章摘要不能为空", trigger: "blur" },
        { max: 500, message: "摘要不能超过500个字符", trigger: "blur" },
      ],
      content: [
        { required: true, message: "文章内容不能为空", trigger: "blur" },
      ],
      coverImage: [
        {
          validator: (rule, value, callback) => {
            if (value && !/^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test(value)) {
              callback(new Error("请输入有效的URL地址"));
            } else {
              callback();
            }
          },
          trigger: "blur",
        },
      ],
      status: [
        { required: true, message: "请选择文章状态", trigger: "blur" },
      ],
      commentStatus: [
        { required: true, message: "请选择评论状态", trigger: "blur" },
      ],
      publishedAt: [
        {
          validator: (rule, value, callback) => {
            // 如果状态是已发布，则发布时间必填
            if (form.status === "published" && !value) {
              callback(new Error("发布时间不能为空，不能早于当前时间"));
            } else {
              callback();
            }
          },
          trigger: "blur",
        },
      ],
      metaData: [
        {
          validator: (rule, value, callback) => {
            if (value) {
              try {
                JSON.parse(value);
                callback();
              } catch (e) {
                callback(new Error("元数据必须是有效的JSON格式"));
              }
            } else {
              callback();
            }
          },
          trigger: "blur",
        },
      ],
    };

    // 生成slug（URL如果为空）
    const generateSlugIfEmpty = () => {
      if (!form.slug && form.title) {
        form.slug = form.title
          .toLowerCase()
          .replace(/\s+/g, "-")
          .replace(/[^\w\-]+/g, "")
          .replace(/\-\-+/g, "-")
          .replace(/^-+/, "")
          .replace(/-+$/, "");
      }
      // 更新父组件的 modelValue
      emit('update:modelValue', { ...form });
    };

    // 处理封面上传成功
    const handleCoverUploadSuccess = (response, file) => {
      // 根据实际API响应结构调整，假设返回的是图片URL
      form.coverImage = response.data?.url || response.url || '';
      emit('update:modelValue', { ...form });
    };

    // 文章重置表单
    const resetForm = () => {
      articleFormRef.value?.resetFields();
      form.title = "";
      form.slug = "";
      form.summary = "";
      form.coverImage = "";
      form.content = "";
      form.status = "draft";
      form.commentStatus = "open";
      form.isTop = "0";
      form.metaData = "";
      form.publishedAt = "";
      emit('update:modelValue', { ...form });
    };

    // 提交表单
    const submitForm = async () => {
      articleFormRef.value.validate(async (valid) => {
        if (valid) {
          emit('submit', { ...form });
        }
      });
    };

    return {
      form,
      articleFormRef,
      articleRules,
      defaultTime,
      generateSlugIfEmpty,//生成slug
      handleCoverUploadSuccess,//处理封面上传成功
      resetForm,//重置表单
      submitForm,//提交表单
      isEditMode,
      isRichTextEditor,//富文本编辑器
      toggleEditor,//切换编辑器
      editorOption // 添加editorOption到返回对象中
    };
  },
};
</script>

<style scoped>
.article-form-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  animation: fadeIn 0.5s ease-in-out;
}

.article-form-card {
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  border: none;
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  background: linear-gradient(145deg, #f8f9fa, #ffffff);
}

.article-form-card:hover {
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px 0;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 50%;
  padding: 10px;
}

.header-title {
  font-size: 22px;
  font-weight: 700;
  color: #2c3e50;
  background: linear-gradient(90deg, #409eff, #3498db);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.header-tag {
  margin-left: auto;
  font-weight: 600;
  border-radius: 20px;
  padding: 5px 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.article-form {
  padding: 30px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 15px;
}

.title-input :deep(.el-input__inner) {
  font-size: 18px;
  font-weight: 600;
  padding: 15px;
  border-radius: 10px;
  border: 2px solid #e9ecef;
  transition: all 0.3s ease;
}

.title-input :deep(.el-input__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.summary-textarea :deep(.el-textarea__inner) {
  border-radius: 10px;
  border: 2px solid #e9ecef;
  padding: 15px;
  font-size: 15px;
  line-height: 1.6;
  transition: all 0.3s ease;
}

.summary-textarea :deep(.el-textarea__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.content-textarea :deep(.el-textarea__inner) {
  border-radius: 10px;
  border: 2px solid #e9ecef;
  padding: 20px;
  font-size: 15px;
  line-height: 1.7;
  transition: all 0.3s ease;
  /* 设置固定高度，超出范围后不再变化 */
  min-height: 500px;
  max-height: 500px;
}

.content-textarea :deep(.el-textarea__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.metadata-textarea :deep(.el-textarea__inner) {
  border-radius: 10px;
  border: 2px solid #e9ecef;
  padding: 15px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 14px;
  transition: all 0.3s ease;
}

.metadata-textarea :deep(.el-textarea__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.form-item-hint {
  margin-top: 8px;
}

.editor-toggle-btn {
  margin-bottom: 15px;
}

.rich-text-editor {
  border: 2px solid #e9ecef;
  border-radius: 10px;
  padding: 15px;
  /* 设置固定高度，超出范围后不再变化 */
  height: 500px;
  max-height: 500px;
  background-color: #fff;
  overflow: auto;
}

/* 添加一个新的包装器类来控制富文本编辑器容器的高度 */
.editor-wrapper {
  height: 500px;
  max-height: 500px;
  margin-bottom: 20px; /* 添加底部间距防止与下方元素重叠 */
}

.form-spacing {
  height: 50px; /* 添加额外的间距 */
}

.cover-upload-container {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.cover-upload-container .el-upload {
  flex-shrink: 0;
}

.cover-preview {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 12px;
}

.cover-image {
  width: 200px;
  height: 130px;
  border-radius: 12px;
  border: 2px solid #e9ecef;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  overflow: hidden;
}

.cover-image:hover {
  transform: scale(1.03) translateY(-3px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  color: #909399;
  font-size: 28px;
  border-radius: 12px;
}

.remove-cover-btn {
  margin-top: 8px;
  border-radius: 8px;
  padding: 8px 15px;
  transition: all 0.3s ease;
}

.remove-cover-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(245, 108, 108, 0.3);
}

.status-radio-group {
  width: 100%;
  display: flex;
  gap: 15px;
}

.status-radio-group :deep(.el-radio-button__inner) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 10px !important;
  border: 2px solid #dcdfe6 !important;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05) !important;
  font-weight: 500;
  transition: all 0.3s ease;
}

.status-radio-group :deep(.el-radio-button.is-active .el-radio-button__inner) {
  background: linear-gradient(135deg, #409eff, #3498db);
  border-color: #409eff !important;
  color: white;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3) !important;
}

.publish-date-picker :deep(.el-input__inner) {
  border-radius: 10px;
  border: 2px solid #e9ecef;
  padding: 12px 15px;
  transition: all 0.3s ease;
}

.publish-date-picker :deep(.el-input__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.form-actions {
  text-align: right;
  padding: 20px 0 10px;
  margin-top: 30px;
  border-top: 1px solid #eee;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
}

.action-buttons .el-button {
  padding: 14px 24px;
  border-radius: 10px;
  font-weight: 600;
  font-size: 15px;
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
}

.action-buttons .el-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.12);
}

.submit-button {
  background: linear-gradient(135deg, #409eff, #3498db);
  border: none;
}

.submit-button:hover {
  background: linear-gradient(135deg, #3498db, #409eff);
  box-shadow: 0 8px 20px rgba(52, 152, 219, 0.4) !important;
}

@media (max-width: 768px) {
  .article-form-container {
    padding: 15px;
  }
  
  .article-form-card {
    border-radius: 12px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-tag {
    margin-left: 0;
  }
  
  .article-form {
    padding: 20px 15px;
  }
  
  .cover-upload-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .form-actions {
    padding-right: 0;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 12px;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin-right: 0;
  }
  
  .header-title {
    font-size: 20px;
  }
  
  .header-tag {
    display: none;
  }
  
  .status-radio-group {
    flex-direction: column;
    gap: 10px;
  }
  
  .status-radio-group :deep(.el-radio-button) {
    width: 100%;
  }
  
  .status-radio-group :deep(.el-radio-button__inner) {
    justify-content: center;
    width: 100%;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}
</style>